﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using CoolCode.Linq;
using CoolCode.Linq.Expressions;
using CoolCode.Entities;

namespace CoolCode.Services
{
    public static class QueryHelper
    {
        public static Expression<Func<Inspection, bool>> PassCondition(ProductCriterion criterion)
        {
            Expression<Func<Inspection, bool>> cond = c =>
                (c.ProductSpec == criterion.ProductSpec) &&
                (c.ODFar >= criterion.MinODFar && c.ODFar <= criterion.MaxODFar) &&
                (c.ODClose >= criterion.MinODClose && c.ODClose <= criterion.MaxODClose) &&
                (c.ConeHeight >= criterion.MinConeHeight && c.ConeHeight <= criterion.MaxConeHeight) &&
                (c.SacculusLength >= criterion.MinSacculusLength && c.SacculusLength <= criterion.MaxSacculusLength) &&
                (c.SacculusStretch >= criterion.MinSacculusStretch && c.SacculusStretch <= criterion.MaxSacculusStretch) &&
                (c.ODStressTest2 >= criterion.MinODStressTest2 && c.ODStressTest2 <= criterion.MaxODStressTest2) &&
                (c.StressTestLength >= criterion.MinStressTestLength && c.StressTestLength <= criterion.MaxStressTestLength);
            return cond;
        }

        public static Expression<Func<Inspection, bool>> PassCondition(List<ProductCriterion> criterions)
        {
            Expression<Func<Inspection, bool>> cond = c => false;
            if (criterions == null || criterions.Count == 0)
                throw new Exception("产品标准的相关数据丢失！"); 
            foreach (var criterion in criterions)
            { 
                cond = cond.Or(PassCondition(criterion)); 
            } 
            return cond;
        }

        public static Expression<Func<Inspection, bool>> NGCondition(List<ProductCriterion> criterions)
        {
            var cond = PassCondition(criterions).Not();
            return cond;
        }

        /// <summary>
        /// 建立 Between 查询条件
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="q">动态查询条件创建者</param>
        /// <param name="property">属性</param>
        /// <param name="from">开始值</param>
        /// <param name="to">结束值</param>
        /// <returns></returns>
        public static IQueryBuilder<T> Between<T>(this IQueryBuilder<T> q, Expression<Func<T, decimal>> property, string from, string to)
        {
            decimal dfrom, dto;
            decimal.TryParse(from, out dfrom);
            decimal.TryParse(to, out dto);
            if (dfrom <= dto)
            {
                if (dto != 0m)
                {
                    return q.Between<T>(property, dfrom, dto);
                }
            }
            return q;
        }
    }
}
